package com.cloud.phone.task

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.cloud.phone.MainActivity
import com.cloud.phone.base.BaseApp
import com.cloud.phone.bean.PermissionRqInfo
import com.cloud.phone.constants.Constants
import com.cloud.phone.manager.FileManager
import com.cloud.phone.task.SendMsgUtils.sendMsgBean
import com.cloud.phone.task.bean.ProxyDataBean
import com.cloud.phone.task.bean.ProxyInfoBean
import com.cloud.phone.task.bean.ProxyVpnTaskBean
import com.cloud.phone.task.taskCongfig.TaskTypeConfig
import com.cloud.phone.utils.AppUtils
import com.cloud.phone.utils.AppUtils.Companion.getRunningProcesses
import com.cloud.phone.utils.AppUtils.Companion.openApp
import com.cloud.phone.utils.DownLoadUtils
import com.cloud.phone.utils.MediaScannerHelper
import com.cloud.phone.utils.ProxyUtils
import com.cloud.phone.utils.ProxyUtils.getProxyIp
import com.cloud.phone.utils.ProxyUtils.getSocksUrl
import com.cloud.phone.view.TsUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus

/**
 * @auth: njb
 * @date: 2024/6/5 10:06
 * @desc: 描述
 */
class ProxyTaskManager(var activity: MainActivity) {
    private val TAG = "WebsocketProxy"
    fun onHandleMsg(msg: String) {
        LogUtils.d(TAG, "===接收到的数据为===$msg")
        if (TextUtils.isEmpty(msg)) {
            return
        }
        try {
            val baseProxyBean = GsonUtils.fromJson(msg, ProxyVpnTaskBean::class.java)
            val code = baseProxyBean.code
            if (code != 1004) {
                return
            }
            if (Constants.TASK_IS_RUNNING) {
                val task = TaskManager.getInstance().getCurrentTask()
                if (task != null) {
                    LogUtils.e("vpn代理正在执行了！！！！")
                    task.onTaskErr("已有vpn代理任务在执行了,taskType=" + task.getServerTaskTypeByCurrentTaskType())
                }
                return
            }
            if(baseProxyBean.data != null){
                val dataBean = baseProxyBean.data
                LogUtils.e(TAG, "===解析到的数据为1111===${GsonUtils.toJson(dataBean)}")
                createTaskInTaskManager(dataBean)
            }
        } catch (e: Exception) {
            e.printStackTrace()
//            TsUtils.showTips("Ip任务解析失败："+e.cause+"/"+e.message)
        }
    }

    private fun createTaskInTaskManager(taskBean: ProxyDataBean?) {
        taskBean?.let {
            try {
                setTaskType(it.taskType, taskBean)
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtils.e("数据解析异常->>>" + e.message)
            }
        }
    }

    private fun setTaskType(taskType: Int, taskDataBean: ProxyDataBean?) {
        try {
            taskDataBean?.apply {
                val proxyInfo = GsonUtils.fromJson(taskDataBean.json, ProxyInfoBean::class.java)
                when (taskType) {
                    TaskTypeConfig.PROTECT_APP_PROCESS -> {//进程守护任务类型为5
                        Constants.VPN_TASK_TYPE = taskType
                        Constants.TASK_TYPE = 5
                        LogUtils.d(TAG, "===解析到的任务数据为55555===" + GsonUtils.toJson(taskDataBean))
                        proxyInfo?.let {
                            if (it.apks?.isNotEmpty() == true) {
                                val apkInfo = it.apks
                                apkInfo?.let {
                                    val appInfo = getRunningProcesses(activity)
                                    for (i in apkInfo) {
                                        TsUtils.showTips("===需要打开的包名为===$i")
                                        if (!appInfo.apkName.contains(i)) {
                                            openApp(activity, i)
                                        }
                                        proxyInfo.apks = apkInfo
                                    }
                                }
                            } else {
                                LogUtils.d(TAG, "app未打开，包名为空")
                                proxyInfo.apks = null
                            }
                            it.id = taskDataBean.id
                            sendMsgBean(it)
                        }
                    }

                    TaskTypeConfig.PROXY_IP -> {//ip代理任务类型为4
                        Constants.VPN_TASK_TYPE = taskType
                        Constants.TASK_TYPE = 4
                        LogUtils.d(TAG, "===解析到的任务数据为44444===" + GsonUtils.toJson(taskDataBean))
                        proxyInfo?.let {
                            LogUtils.d(TAG, "===设置的vpn状态为11111===" + Constants.IS_MY_VPN_SERVICE_RUNNING)
                            it.id = taskDataBean.id
                            ProxyUtils.setTaskId(it.id)
                            if (!TextUtils.isEmpty(it.ip) && !TextUtils.isEmpty(it.account)
                                && !TextUtils.isEmpty(it.password)
                            ) {
                                val proxyUrl = ProxyUtils.ProxySocks(
                                    it.account,
                                    it.password,
                                    it.ip,
                                    it.port
                                )
                                Constants.PROXY_SOCKS_URL = proxyUrl
                                MsgTaskManger.showLog(proxyUrl)
                                LogUtils.d(TAG, "===收到的代理ip为===${proxyUrl}")
                                ProxyUtils.setSocksUrl(proxyUrl)
                                LogUtils.d(TAG, "打开vpn")
                                ProxyUtils.setProxyIp(it.ip)
                                val proIp = getProxyIp()
                                TsUtils.showTips("收到代理ip任务：${it.ip}")
                                LogUtils.d(TAG, "===代理地址为===" + proIp + "===收到的ip===" + it.ip)
//                                    AppUtils.launchApp(BaseApp.app,BaseApp.app.packageName)
                                Thread.sleep(5000)
                                EventBus.getDefault().post(PermissionRqInfo())
                                Constants.TASK_STATUS = true
                                Constants.TASK_IS_RUNNING = true
                            } else {
                                AppUtils.launchApp(BaseApp.app,BaseApp.app.packageName)
                                LogUtils.d(TAG, "停止vpn")
                                TsUtils.showTips("收到停止代理IP任务")
                                Thread.sleep(5000)
                                AppUtils.stopVpn(activity)
                                stopVpnProxy(proxyInfo)
                                Constants.TASK_STATUS = true
                                Constants.TASK_IS_RUNNING = true
                                sendMsgBean(it)
                            }
                        }
                    }

                    TaskTypeConfig.UPDATE_APK -> { //应用更新的类型为6
                        Constants.VPN_TASK_TYPE = taskType
                        Constants.TASK_TYPE = 6
                        LogUtils.d(TAG, "===解析到的任务数据为66666===" + GsonUtils.toJson(taskDataBean))
                        proxyInfo?.let {
                            //线上的apk版本比本地的aok版本高
                            if (AppUtils.checkVersion(it,activity)) {
                                MainScope().launch {
                                    withContext(Dispatchers.IO) {
                                        if(!TextUtils.isEmpty(proxyInfo.url)){
                                            DownLoadUtils.downLoadApk(proxyInfo.url, activity)
                                        }
                                    }
                                }
                            }
                        }
                    }

                    TaskTypeConfig.MEDIA_SCANNER ->{//刷新图库
                        Constants.VPN_TASK_TYPE = taskType
                        Constants.TASK_TYPE = 16
                        var filePath: String
                        LogUtils.d(TAG, "===解析到的任务数据为16===" + GsonUtils.toJson(taskDataBean))
                        proxyInfo?.let {
                            MainScope().launch {
                                withContext(Dispatchers.IO){
                                    LogUtils.d(TAG,"===文件目录为==="+it.filePath)
                                     filePath = FileManager.appendSlashIfNeeded(it.filePath)
                                }
                                withContext(Dispatchers.Main) {
                                    delay(10000)
                                    if(filePath.isNotEmpty()){
                                        MediaScannerHelper.refreshFolder(filePath,it)
                                        Constants.TASK_STATUS = true
                                        Constants.TASK_IS_RUNNING = true
                                        it.id = taskDataBean.id
                                        sendMsgBean(it)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun startActivity(context: Context) {
        val intent = Intent(context, MainActivity::class.java)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    private fun stopVpnProxy(proxyInfo: ProxyInfoBean?) {
        proxyInfo?.let {
            it.ip = ""
            it.account = ""
            it.port = 0
            it.password = ""
        }
        LogUtils.d(TAG, "===代理地址为===" + getProxyIp() + "===代理url为===" + getSocksUrl())
    }
}